package com.xiaoqianxin.api.service;

import com.xiaoqianxin.api.repositories.TeamRepository;
import com.xiaoqianxin.entity.Team;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;


/**
 * 队伍服务类
 */
@Service
public class TeamService {

    private static Logger LOG = LoggerFactory.getLogger(TeamService.class);

    @Autowired
    private TeamRepository teamRepository;

    /**
     * 分页查询队伍
     *
     * @param id       队伍id
     * @param type     队伍类型
     * @param name     队伍名字
     * @param pageable 分页参数
     * @return 查询结果
     */
    public Page<Team> query(String id, String type, String name, Pageable pageable) {
        LOG.debug("查询队伍,id={},type={},name={},pageable={}", id, type, name, pageable);
        Specification<Team> specification = (Specification<Team>) (root, query, criteriaBuilder) -> {
            Expression<String> id1 = root.get("id");
            Expression<String> type1 = root.get("type");
            Expression<String> name1 = root.get("name");
            List<Predicate> predicates = new ArrayList<>();
            if (!StringUtils.isEmpty(id)) {
                predicates.add(id1.in(id));
            }
            if (!StringUtils.isEmpty(type)) {
                predicates.add(type1.in(type));
            }
            if (!StringUtils.isEmpty(name)) {
                predicates.add(name1.in(name));
            }
            query.where(predicates.toArray(new Predicate[0]));
            return null;
        };
        Page<Team> page = teamRepository.findAll(specification, pageable);
        LOG.debug("查询队伍,结果={}", page);
        return page;
    }


}
